#!/usr/bin/python3
# -*- coding:utf-8 -*-

# ~Authors: chenwenke

# 认证 权限 访问频率

import time
from app01 import models
from rest_framework.authentication import BaseAuthentication
from rest_framework.throttling import BaseThrottle
from rest_framework.permissions import BasePermission
from rest_framework import exceptions



class Authentication(BaseAuthentication):
    """认证"""
    def authenticate(self,request):
        token = request.META.get("HTTP_TOKEN")
        token_obj = models.TokenModel.objects.filter(token=token).first()
        if not token_obj:
            raise exceptions.AuthenticationFailed("验证失败")
        elif token_obj.expire_date < time.time():
            raise exceptions.AuthenticationFailed("token过期")
        return token_obj.user,token_obj.token



class VipPermission(BasePermission):
    """权限"""
    def has_permission(self,request,view):
        pass


class MyThrottle(BaseThrottle):
    """频率"""
    visitor_dict = {}

    def __init__(self):
        self.history = None

    def allow_request(self, request, view):

        ip = request.META.get('REMOTE_ADDR')
        ctime = time.time()
        if ip not in self.visitor_dict:
            self.visitor_dict[ip] = [ctime,]
            return True

        history = self.visitor_dict[ip]
        self.history = history
        while history and ctime - history[-1] > 60:
            history.pop()

        if len(history) < 3:
            history.insert(0,ctime)
            return True
        # print(history)
        return False

    def wait(self):
        ctime = time.time()
        return 60 - (ctime - self.history[-1])


